const { Message } = require("../models");
const { NotFound } = require("http-errors");
const { getSocketInstance } = require("../socket/socketInfo");

let obj = {
  title: "",
  content: "",
  senderId: "",
  receiverId: "system",
  level: "1",
  type: "2",
  isWebSocket: "1",
  status: "2",
  routParams: "",
};
async function socketMsg(socket, msg, data, eventName = "bunessHandle") {
  if (socket) {
    socket.emit(eventName, { message: msg, data });
  } else {
    throw new NotFound(`socket未连接。`);
  }
  const {
    title,
    content,
    senderId,
    receiverId,
    level,
    type,
    isWebSocket,
    status,
    routParams,
  } = data;
  if (
    !title ||
    !content ||
    !senderId ||
    !receiverId ||
    !level ||
    !isWebSocket ||
    !status ||
    !type
  ) {
    // throw new Error('缺少必要参数');
    throw new NotFound(`消息入库失败，缺少必要参数${data}`);
  }

  try {
    const msgParams = {
      title: data.title,
      content: data.content,
      senderId: data.senderId,
      receiverId: data.receiverId,
      level: data.level,
      type: data.type,
      isWebSocket: data.isWebSocket,
      status: data.status,
      routParams: data.routParams || "",
    };

    const msgData = await Message.create(msgParams);
    socket.emit(eventName, {
      message: "插入数据到消息数据库表成功",
      data: msgData,
    });
  } catch (error) {
    console.log("error", error);
    socket.emit(eventName, {
      message: "插入数据到消息数据库表失败",
      data: error,
    });
    throw new NotFound(`消息入库失败，${error}`);
  }
}
async function setSocket(
  socket,
  title,
  content,
  senderId,
  routParams,
  eventName = "bunessHandle"
) {
  obj.title = title;
  obj.content = content;
  obj.senderId = senderId;
  obj.routParams = routParams;
  await socketMsg(socket, obj.content, obj, eventName);
}

module.exports = {
  socketMsg,
  setSocket,
};
